package com.imooc.bilibili.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.imooc.bilibili.config.ConfirmConfig;
import com.imooc.bilibili.dao.UserMomentsDao;
import com.imooc.bilibili.domain.UserMoments;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Service
public class UserMomentsService {

    @Autowired
    private UserMomentsDao userMomentsDao;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 新增用户动态
     * @param userMoments
     */
/*    public void addUserMoments(UserMoments userMoments) throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
        userMoments.setCreateTime(new Date());
        userMomentsDao.addUserMoments(userMoments);
        DefaultMQProducer producer = (DefaultMQProducer) applicationContext.getBean("momentsProducer");
        Message msg = new Message(UserMomentsConstant.TOPIC_MOMENTS, JSONObject.toJSONString(userMoments).getBytes(StandardCharsets.UTF_8));
        RocketMQUtil.syncSendMsg(producer,msg);
    }*/
    public void addUserMoments(UserMoments userMoments){
        userMoments.setCreateTime(new Date());
        userMomentsDao.addUserMoments(userMoments);
        Message msg = new Message(JSONObject.toJSONString(userMoments).getBytes(StandardCharsets.UTF_8));
        CorrelationData correlationData = new CorrelationData("1");
        RabbitTemplate rabbitTemplate = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");
        rabbitTemplate.convertAndSend(ConfirmConfig.MOMENTS_EXCHANGE_NAME,
                ConfirmConfig.MOMENTS_ROUTING_KEY,msg,correlationData);
    }


    /**
     * 获取用户订阅的动态
     * @return
     */
    public List<UserMoments> getUserSubscribedMoments(Long userId) {
        String key = "subscribed-" + userId;
        String str = stringRedisTemplate.opsForValue().get(key);
        List<UserMoments> userMoments = JSONArray.parseArray(str, UserMoments.class);
        return userMoments;
    }
}
